<template>
  <div class="container">
    <el-drawer
      custom-class="wxkj-drawer"
      :title="drawerTitle"
      :visible.sync="drawerShow"
      :before-close="drawerClose"
      size="500"
    >
      <div class="drawer-content">
        <el-form

          ref="form"
          :model="form"
          :rules="formRules"
          label-width="120px"
        >
          <el-form-item label="专场标题：" required prop="title">
            <el-input v-model.trim="form.title" />
          </el-form-item>
          <el-form-item label="时间：" required prop="date">
            <el-date-picker
              v-model="form.date"
              style="width: 100%"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>
          <el-form-item label="专场头部图片：" required prop="imageFileId">
            <upload-cropper
              ref="BannerUploadCropper"
              class="banner-upload-cropper"
              :enlarge="2"
              mode="100% auto"
              :auto-crop-width="1920"
              :auto-crop-height="500"
              :fixed-number="[3.84, 1]"
              :init-img="form.imageFileId_dictText"
              :tip-content="'只支持JPG、PNG格式,建议使用大小不要超过1000k、1920*500像素的图片'"
              @upload="getBannerImageId"
            />
          </el-form-item>

          <!--          <el-form-item label="专场视频：" required prop="videoId">
            <upload-video ref="uploadVideo" :init-url="form.videoId_dictText" @upload="getVideoId" />
          </el-form-item>-->

          <el-form-item label="基本信息介绍：" required prop="introduce">
            <el-input
              v-model="form.introduce"
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
            />
          </el-form-item>

          <el-form-item label="相关图片：" required prop="imageBaseInfoId">
            <upload-cropper
              ref="uploadBaseInfoCropper"
              class="baseInfo-upload-cropper"
              :fixed-box="true"
              :limit="5"
              :enlarge="2"
              :auto-crop-width="315"
              :fixed-number="[1.5, 1]"
              :init-img="form.urlList"
              :tip-content="'只支持JPG、PNG格式, 建议使用大小不要超过500k、630*420像素的图片'"
              @upload="getbaseInfoImageId"
            />
          </el-form-item>
          <el-form-item label="多个职位投递：" required prop="imageBaseInfoId">
            <el-switch v-model="form.repeatFlag" active-color="#13ce66" inactive-color="#ff4949" />
          </el-form-item>
          <el-form-item label="岗位发布管控：">
            <el-switch v-model="form.postShelfManage" active-color="#13ce66" inactive-color="#ff4949" />
          </el-form-item>
          <div class="drawer-form-buttom-group">
            <el-button type="primary" :loading="loading" @click="submitForm()">保存</el-button>
            <el-button @click="drawerClose()">取消</el-button>
          </div>
        </el-form>
      </div>
      <!-- <cropper ref="cropper" /> -->
    </el-drawer>
  </div>
</template>

<script>
import { addSpecialSession, editSpecialSession } from '@/api/special-session'
import uploadCropper from '@/components/uploadCropper'
import uploadVideo from '@/components/uploadVideo'
export default {
  name: '',
  components: { uploadCropper, uploadVideo },
  props: {},
  data() {
    var validateUploadImg = (rule, value, callback) => {
      if (value === '') {
        this.$refs.BannerUploadCropper.uploadError(true)
        callback(new Error('请上传专场图片'))
      }
      callback()
    }
    var validateUploadeBaseInfoImg = (rule, value, callback) => {
      if (value === '') {
        this.$refs.uploadBaseInfoCropper.uploadError(true)
        callback(new Error('请专场基本信息介绍图片'))
      }
      callback()
    }
    var validateUploadVideo = (rule, value, callback) => {
      console.log(value, 123)
      if (!value || value === '') {
        this.$refs.uploadVideo.uploadError(true)
        callback(new Error('请上传视频'))
      } else {
        callback()
      }
    }
    return {
      // 限制
      pickerOptions: {
        disabledDate: (time) => {
          if (!this.form.id) {
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      },
      initImg: '',
      drawerTitle: '新增专场',
      drawerShow: false,
      loading: false,
      form: {
        title: '',
        date: '',
        introduce: '',
        repeatFlag: false,
        postShelfManage: false,
        imageFileId: '',
        videoId: '',
        imageBaseInfoId: ''
      },
      formRules: {
        title: [{ required: true, message: '专场标题不能为空' }],
        date: [{ required: true, message: '时间不能为空' }],
        introduce: [{ required: true, message: '专场介绍不能为空' }],
        imageFileId: [{ validator: validateUploadImg }],
        // videoId: [{ validator: validateUploadVideo }],
        imageBaseInfoId: [{ validator: validateUploadeBaseInfoImg }]
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 销毁
  destroyed() {},
  // 方法
  methods: {
    // 打开
    show(title, data) {
      this.drawerTitle = title
      if (data) {
        // data.date = [new Date(data.startTime), new Date(data.endTime)]
        this.$nextTick(() => {
          this.$set(this.form, 'date', [data.startTime, data.endTime])
          this.$forceUpdate()
        })

        const urls = data.imageBaseInfoId_dictText.split(',')
        const ids = data.imageBaseInfoId.split(',')
        const list = []
        for (let i = 0; i < urls.length; i++) {
          list.push({
            url: urls[i],
            id: ids[i]
          })
        }
        data.imageFileId_dictText =
          data.imageFileId_dictText + '?r=' + Math.random()
        data.urlList = list
        this.form = data
      } else {

      }
      this.drawerShow = true
    },
    // 关闭
    drawerClose() {
      this.$emit('refresh')
      this.$refs.form.resetFields()
      this.loading = false
      this.form = {
        title: '',
        date: [],
        introduce: '',
        repeatFlag: false,
        postShelfManage: false,
        imageFileId: '',
        imageBaseInfoId: ''
      }
      this.$refs.uploadBaseInfoCropper.resetUpload()
      this.$refs.BannerUploadCropper.resetUpload()
      this.$refs.uploadVideo.resetUpload()
      this.drawerShow = false
    },

    // 提交
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const form = this.form
          const date = form.date
          form.startTime = date[0]
          form.endTime = date[1]
          if (form.id) {
            editSpecialSession(form).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })

              this.drawerClose()
            }).catch(() => {
              this.loading = false
            })
          } else {
            addSpecialSession(form).then((res) => {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.drawerClose()
            }).catch(() => {
              this.loading = false
            })
          }
        } else {
          return false
        }
      })
    },
    // banner id
    getBannerImageId(id) {
      this.form.imageFileId = id
      this.$refs.form.clearValidate('imageFileId')
    },
    // 专场基本信息介绍图片id 以,分割
    getbaseInfoImageId(id) {
      this.form.imageBaseInfoId = id
      this.$refs.form.clearValidate('imageBaseInfoId')
    },
    getVideoId(id) {
      this.form.videoId = id
      this.$refs.form.clearValidate('videoId')
    }
  }
}
</script>
<style lang="scss">
.banner-upload-cropper {
  .upload-img {
    .el-upload {
      width: 340px;
      height: 88.5px;
      line-height: 88.5px;
    }
  }
}

.baseInfo-upload-cropper {
  .upload-img {
    .el-upload {
      width: 150px;
      height: 100px;
      line-height: 100px;
    }
  }
}
</style>
